﻿/*********************************************************
 * 开发人员：网魂小兵
 * 创建时间：2012/6/14 22:36:14
 * 运行环境：.NET Framework 4.0.30319.17020
 * 修改历史：
 * 
 * *******************************************************/

namespace Mozlite.WebUI.Ajax
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Services;
    using System.Reflection;

    /// <summary>
    /// Asp.net ajax 4.0页面基类。
    /// </summary>
    public abstract class AjaxBasePage : BasePage
    {
        /// <summary>
        /// 初始化类<see cref="T:Mozlite.Web.AjaxBasePage"/>。
        /// </summary>
        public AjaxBasePage()
        {

        }

        /// <summary>
        /// 重写初始化方法，注册AJAX方法。
        /// </summary>
        /// <param name="e">事件实例。</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            StringBuilder javascript = new StringBuilder();
            var type = this.GetType();
            foreach (var methodInfo in type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy))
            {
                var attributes = methodInfo.GetCustomAttributes(typeof(WebMethodAttribute), true);
                if (attributes.Length == 0)
                    continue;
                javascript.AppendFormat("window.{0}=function(", methodInfo.Name.ToCamelCase());
                var parameters = "";
                var json = "";
                foreach (var parameter in methodInfo.GetParameters())
                {
                    if (parameters.Length > 0)
                    {
                        parameters += ", ";
                        json += ", ";
                    }
                    parameters += parameter.Name;
                    json += string.Format("{0}:{0}", parameter.Name);
                }
                javascript.Append(parameters);
                if (parameters.Length > 0)
                    javascript.Append(", ");
                javascript.AppendFormat("onSuccess, onError){{$.aspnetAjax('{0}', {{{1}}}, onSuccess, onError);}}", methodInfo.Name, json);
            }
            if (Request.Browser.IsBrowser("IE") && Request.Browser.Version.ToDouble() < 8.0)
                ClientScript.RegisterClientScriptResource(typeof(AjaxBasePage), "Mozlite.WebUI.Ajax.json2.js");
            ClientScript.RegisterClientScriptResource(typeof(AjaxBasePage), "Mozlite.WebUI.Ajax.jquery.ajax.js");
            if (javascript.Length > 0)
                ClientScript.RegisterClientScriptBlock(type, "AspNetAjax4.0", javascript.ToString()+"\r\n", true);
        }
    }
}
